package com.team2.cyber_eye.background_task;

import com.team2.cyber_eye.ActivityHelpers.Util;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;

public class CheckInternetConnectionTask extends AsyncTask<Void, Void, String> {
	
	String statusMsg = "";
	
	public interface LoadingTaskFinishedListener {
		void onTaskFinished(String internetConnectionStatus); // If you want to pass something back to the listener add a param to this method
	}
	
	// This is the progress bar you want to update while the task is in progress
	// This is the listener that will be told when this task is finished
	private final LoadingTaskFinishedListener finishedListener;
	private final Activity creator;
	
	/**
	 * A Loading task that will load some resources that are necessary for the app to start
	 * @param progressBar - the progress bar you want to update while the task is in progress
	 * @param finishedListener - the listener that will be told when this task is finished
	 */
	public CheckInternetConnectionTask(LoadingTaskFinishedListener finishedListener, Activity creator)
	{
		this.finishedListener = finishedListener;
		this.creator = creator;
	}

	@Override
	protected void onPostExecute(String status) {
		super.onPostExecute(status);
		finishedListener.onTaskFinished(status); // Tell whoever was listening we have finished
	}

	@Override
	protected String doInBackground(Void... params) {
		try {
			synchronized (this) {
				wait(3000);
			}
			
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		}
		ConnectivityManager conMan = (ConnectivityManager) creator.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = conMan.getActiveNetworkInfo();
		if (ni == null)
		{
			Util.setInternetConnected(false);
			statusMsg = "No Internet Connection";
		}else{
			Util.setInternetConnected(true);
			statusMsg = "Connection Available";
		}
		
		return statusMsg;
	}
}
